package com.yjq.blog.user.controller;

import com.yjq.blog.enums.ErrorCodeEnum;
import com.yjq.blog.user.constant.CodeConstant;
import com.yjq.blog.user.service.LoginService;
import com.yjq.blog.user.vo.UserLoginVO;
import com.yjq.blog.user.vo.UserRegistryVO;
import com.yjq.blog.vo.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/login")
@Api(tags = "login-controller", value = "/login", description = "登录相关接口")
public class LoginController {

    @Resource
    private LoginService loginService;

    @GetMapping("/login/code")
    public Response<UserLoginVO> codeLogin(String phone, Integer code) {
        if (StringUtils.isBlank(phone)) {
            return Response.fail(ErrorCodeEnum.PHONE_IS_NULL);
        }
        if (code == null) {
            return Response.fail(ErrorCodeEnum.CODE_IS_NULL);
        }
        if (code < CodeConstant.CODE_MIN || code > CodeConstant.CODE_MAX) {
            return Response.fail(ErrorCodeEnum.CODE_ERROR);
        }
        return loginService.login(phone, code);
    }

    @GetMapping("/login/password")
    public Response<UserLoginVO> passwordLogin(String phone, String password) {
        if (StringUtils.isBlank(phone)) {
            return Response.fail(ErrorCodeEnum.PHONE_IS_NULL);
        }
        if (StringUtils.isBlank(password)) {
            return Response.fail(ErrorCodeEnum.PASSWORD_IS_NULL);
        }
        return loginService.passwordLogin(phone, password);
    }

    @PostMapping("/registry")
    public Response<UserLoginVO> registry(@RequestBody UserRegistryVO userRegistryVO) {
        return loginService.registry(userRegistryVO);
    }

    @GetMapping("/code")
    @ApiOperation("获取验证码")
    public Response getCode(String phone, String type, HttpServletRequest request) {

        if (StringUtils.isBlank(phone)) {
            return Response.fail(ErrorCodeEnum.PHONE_IS_NULL);
        }

        if (StringUtils.isBlank(type)) {
            return Response.fail(ErrorCodeEnum.CODE_TYPE_IS_NULL);
        }

        return loginService.getCode(phone, type, request);
    }


}
